<?php
/**
 * 自定义model基类
 * 2017年3月16日
 */
class MY_Model extends CI_Model{

	public function __construct() {
        parent::__construct();
        $this->load->model('SystemLog_model','syslog');
    }
    /**
     * 自定义数据库查询
     * @param [type] $tablename [表名]
     * @param [type] $data      [插入数据数组]
     * @return [type] [<新增id>]
     */
    function hw_Insert($tablename,$data){
        $data['update_time'] = date('Y-m-d H:i:s', time());
    	$res = $this->db->insert($tablename,$data);
    	return $this->db->insert_id();
    }
    /**
     * 自定义数据库更新
     * @param [type] $tablename [表名]
     * @param [type] $data      [更新信息]
     * @param [type] $where     [更新条件]
     */
    function hw_Update($tablename,$data,$where){
        $data['update_time'] = date('Y-m-d H:i:s',time());
        $res = $this->db->where($where)->update($tablename,$data);
        return $this->db->affected_rows();
    }

    /**
     * 自定义数据库更新 set方法
     * $this->db->set('field', 'field+1', FALSE)
     * @param [type] $tablename [表名]
     * @param [type] $set       [更新信息]
     * @param [type] $where     [更新条件]
     */
    function hw_Update_set($tablename,$where,$set){
        $res = $this->db->set($set['field'],$set['file_edit'],FALSE)->where($where)->update($tablename);
        return $this->db->affected_rows();
    }
    
    /**
     * 自定义数据库删除
     * @param [type] $tablename [表名]
     * @param [type] $where     [删除条件]
     */
    function hw_Delete($tablename,$where){
    	$res = $this->db->where($where)->delete($tablename);
    	return $res;
    }
   
    /**
     * 自定义sql语句查询  多
     * @param  [type] $sql [sql语句]
     * @return [type]      [description]
     */
    function hw_querySqlList($sql){
        $res = $this->db->query($sql)->result_array();
        return $res;
    }

      /**
     * 自定义sql语句查询 单
     * @param  [type] $sql [sql语句]
     * @return [type]      [description]
     */
    function hw_querySql($sql){
        $res = $this->db->query($sql)->row_array();
        return $res;
    }

     /**
     * 自定义数据库查询
     * @param [type] $table  [表名]
     * @param [type] $where  [查询条件]
     * @param [type] $fileds [查询范围]
     * @return [type] [<多条记录>]
     */
    function hw_getList($tablename,$where,$select='*',$orderby = 'create_time desc'){
        $res = $this->db->where($where)->select($select)->order_by($orderby)->get($tablename)->result_array();
        return $res;
    }
  
    /**
     * 自定义数据库查询 
     * @param [type] $table  [表名]
     * @param [type] $where  [查询条件]
     * @param [type] $fileds [查询范围]
     * @return [type] [<多条记录>]
     */
    function hw_getList_sum($tablename,$where,$select='*'){
        $res = $this->db->where($where)->count_all_results($tablename);
        return $res;
    }

    /**
     * 自定义数据库查询 limit
     * @param [type] $table  [表名]
     * @param [type] $where  [查询条件]
     * @param [type] $fileds [查询范围]
     * @return [type] [<多条记录>]
     */
    function hw_getList_limit($tablename,$where,$select,$orderby = 'create_time asc',$limit='1000'){
        $res = $this->db->where($where)->select($select)->limit($limit)->order_by($orderby)->get($tablename)->result_array();
        return $res;
    }


   /**
     * 自定义数据库查询 where in 方法
     * @return [type] [<多条记录>]
     */
    function hw_getList_in($tablename,$where_in,$where_inArr,$select,$orderby = 'id asc')
    {
        $res = $this->db->where_in($where_in,$where_inArr)->select($select)->order_by($orderby)->get($tablename)->result_array();
        return $res;
    }

     /**
     * 自定义数据库查询 模糊搜索 like
     * @return [type] [<多条记录>]
     */
    function hw_getList_like($tablename,$where,$select,$like,$like_type='both',$orderby = 'id asc')
    {
        $res = $this->db->where($where)->like($like, $like_type)->select($select)->order_by($orderby)->get($tablename)->result_array();
        return $res;
    }

    /**
     * 自定义数据库查询 模糊搜索 like limit
     * @return [type] [<多条记录>]
     */
    function hw_getList_like_limit($tablename,$where,$select,$like,$limit,$num = 10,$like_type = 'both',$orderby = 'create_time desc')
    {
        $res = $this->db->where($where)->like($like, $like_type)->select($select)->limit($num, $limit)->order_by($orderby)->get($tablename)->result_array();
        return $res;
    }

    function hw_list($tablename,$where,$select,$like,$page,$like_type = 'both',$orderby = 'create_time desc')
    {
        $res = $this->db->where($where)->like($like, $like_type)->select($select)->limit(LINES, ($page-1)*LINES)->order_by($orderby)->get($tablename)->result_array();
        return $res;
    }
    
    /**
     * 统计数据条数 模糊搜索 count
     * @return [type] [<数据条数>]
     */
    function hw_countTable($tablename,$where,$like = array(),$like_type = 'both')
    {
        return $this->db->where($where)->like($like, $like_type)->from($tablename)->count_all_results();
    }

    function hw_count($table, $where, $select, $like=array())
    {
        $list = $this->hw_getList_like($table, $where, $select, $like);
        $res = count($list);
        return $res;
    }



    /**
     * [自定义数据库查询] 模糊查询 or_like
     * @AuthorHTL
     * @DateTime  2017-05-22T09:09:41+0800
     * @param     [string]  $tablename [数据库表明]
     * @param     [array]   $where     [查询条件]
     * @param     [string]  $select    [查询字段]
     * @param     [array]   $or_like   [模糊条件]
     * @param     [string]  $like_type [模糊类型]
     * @param     [string]  $orderby   [排序方法]
     * @return    [array]   $res       [数据库返回数据]
     */
    function hw_getList_orlike($tablename,$where,$select,$or_like,$like_type='both',$orderby = 'id asc')
    {
        $res = $this->db->where($where)->or_like($or_like, $like_type)->select($select)->order_by($orderby)->get($tablename)->result_array();
        return $res;
    }

     /**
     * 自定义数据库查询 分组 group_by
     * $this->db->group_by("title");
     * $this->db->group_by(array("title", "date"));
     * @return [type] [<多条记录>]
     */
    function hw_getList_group($tablename,$where,$select,$group_by,$orderby = 'id asc')
    {
        $res = $this->db->where($where)->group_by($group_by)->select($select)->order_by($orderby)->get($tablename)->result_array();
        return $res;
    }

    /**
     * 自定义数据库查询
     * @return [type] [<单条记录>]
     */
    function hw_getRecord($tablename,$where,$select='*',$orderby = 'create_time asc'){
        $res = $this->db->where($where)->select($select)->order_by($orderby)->get($tablename)->row_array();
        return $res;
    }

    /**
     * 自定义数据库查询 模糊搜索 like
     * @return [type] [<单条记录>]
     */
    function hw_getRecord_like($tablename,$where,$select,$like,$like_type='both',$orderby = 'id asc')
    {
        $res = $this->db->where($where)->like($like, $like_type)->select($select)->order_by($orderby)->get($tablename)->row_array();
        return $res;
    }

    /**
     * [数据库多条记录修改]
     * @AuthorHTL
     * @DateTime  2017-05-15T15:05:45+0800
     * @param     [string] $tablename   [数据库名]
     * @param     [array]  $data        [数据修改内容]
     * @param     [string] $where_in    [条件字段]
     * @param     [array]  $where_inArr [条件数组]
     * @return    [type]                [description]
     */
    function hw_Update_in($tablename,$data,$where_in,$where_inArr){
        $res = $this->db->where_in($where_in,$where_inArr)->update($tablename,$data);
        return $this->db->affected_rows();
    }

    function hw_Update_set_in($tablename,$set,$where_in,$where_inArr){
        $res = $this->db->set($set['field'],$set['file_edit'],FALSE)->where_in($where_in,$where_inArr)->update($tablename);
        return $this->db->affected_rows();
    }
    /**
     * set更新
     * @param  [type] $tablename [description]
     * @param  [type] $where     [description]
     * @param  array  $set       [description]
     * @return [type]            [description]
     */
    function hw_set($tablename,$where,$set)
    {
        
        if(is_array($set)&&!empty($set))
        {
            foreach ($set as $key => $value) 
            {
                
                $this->db->set($value[0],$value[1],$value[2]);

            }

            $this->db->where($where)->update($tablename);

            return $this->db->affected_rows();
        }

        return 0;
    }

    /**
     * 获取返回信息
     * @param  [type] $result [description]
     * @return [type]         [description]
     */
    function getReturn($result){
        if($result){
            $return = array(
                'code'=>1,
                'msg'=>"操作成功",
                );
        }else{
            $return = array(
                'code'=>0,
                'msg'=>"操作失败",
                );
        }
        return $return;
    }

    /**
     * 判断日期格式是否合法
     * @param  [type]  $dateString [description]
     * @return boolean             [description]
     */
    function isDate( $dateString ) {
        return strtotime( date('Y-m-d', strtotime($dateString)) ) === strtotime( $dateString );
    }

    /**
     * 获取更新返回信息
     * @param  [type] $result [description]
     * @return [type]         [description]
     */
    function getUpdateReturn($affected_rows){
        if($affected_rows>0){
            $return = array(
                'code'=>1,
                'msg'=>"操作成功",
                );
        }else{
            $return = array(
                'code'=>0,
                'msg'=>"操作失败",
                );
        }
        return $return;
    }
    /**
     * 获取所有列表
     * @return [type] [description]
     */
    function getAllList($tablename,$shop_token,$select = "*"){
        $where = array('del_status'=>0, 'shop_token'=>$shop_token);
        return $this->hw_getList($tablename,$where,$select);
    }
    /**
     * 根据id返回信息
     * @param  [type] $tablename [description]
     * @param  [type] $id_name   [description]
     * @param  [type] $id_value  [description]
     * @return [type]            [description]
     */
    function getRowById($tablename,$id_name,$id_value,$shop_token,$select = "*"){
        
        $where = array("$id_name"=>$id_value,'shop_token'=>$shop_token);

        return $this->hw_getRecord($tablename,$where,$select);
    }
    /*
    添加后台系统操作日志及日志明细
    $operatorid【操作员id】$operator【操作员姓名】$tablename【操作模块名】,$keys【键值】,$details【详情】,$type【操作类型，0删除，1新增，2编辑，3审核】,$status【操作状态，1成功 0失败】
    $tablename 为操作模块的主表名称，一个操作涉及多个表操作的传递主表的表名和键值,例如新增一款商品的时候同时会操作goods 和 spec 2张表，一款商品可能对应多款规格
    这时候日志记录goods表新插入的数据序号值 和 goods 表表名 ，所有的post数据打包成details即可
    2017.3.27 小黑鼠
    */
    function LogAdd($operatorid,$operator,$tablename,$keys,$details="",$type=1,$status=1){
        if( empty($operator) || empty($tablename) || empty($keys) ){
            return array('code'=>0,'msg'=>'参数丢失');
        }else{
            $data = array(
                'operatorid' => $operatorid,
                'operator' => $operator,
                'tablename' => $tablename,
                'keys' => $keys,
                'type' => $type,
                'status' => $status,
                );
             $res = $this->hw_Insert('log',$data);
             if($res){
                if(!empty($details)){
                     $data = array(
                        'logid' => $res,
                        'details' => $details,
                    );
                    $this->hw_Insert('log_details',$data);
                }
               
                return array('code'=>1,'msg'=>'添加日志成功');
             }else{
                return array('code'=>0,'msg'=>'添加日志失败');
             }
        }  
    }

    /**
     * [获取该数据日志最后修改信息]
     * @AuthorHTL
     * @DateTime  2017-06-08T15:33:50+0800
     * @param     [type] $table [表名]
     * @param     [type] $id    [数据id]
     * @return    [type] $title [操作信息]
     */
    function getLastLog($table, $id)
    {
        $where = array(
            'tablename' => $table,
            'keys' => $id,
            );
        $log = $this->hw_getRecord('log', $where, '*', 'id desc');
        switch ($log['type']) {
            case '0':
                $title = $log['operator'].'删除了该数据';
                break;
            case '1':
                $title = $log['operator'].'新增了该数据';
                break;
            case '2':
                $title = $log['operator'].'编辑了该数据';
                break;
            case '3':
                $title = $log['operator'].'审核了该数据';
                break;
            default:
                $title = '暂无信息';
                break;
        }
        return $title;
    }

    /**
     * [检测字段值是否重复]
     * @AuthorHTL
     * @DateTime  2017-06-08T09:47:08+0800
     * @param     [type] $value      [字段值]
     * @param     [type] $shop_token [商户唯一标示]
     * @param     [type] $table      [操作的数据库表]
     * @param     [type] $string     [字段名，默认为代码字段]
     * @return    [type] $res        [数据库返回结果]
     */
    function codeRepeat($value, $shop_token, $table, $string = 'code')
    {
        $where = array(
            $string => $value,
            'shop_token' => $shop_token,
            'del_status' => '0',
            );
        $res = $this->hw_getList($table, $where, 'id');
        return $res;
    }

    /**
     * [获取订单号]
     * @Author   zt
     * @DateTime 2018-01-02
     * @param    [type]     $id         [用户id]
     * @return   [type]     $orderid    [订单号]
     */
    function getOrderId($id)
    {
        mt_srand((double)microtime() * 1000000);
        $orderid = $id . date('Ymd') . str_pad(mt_rand(1, 99999), 7, '0', STR_PAD_LEFT);
        return $orderid;
    }

    /**
     * [加密函数]
     * @Author   zt
     * @DateTime 2018-09-19
     * @param    [type]     $txt [加密内容]
     * @param    string     $key [description]
     * @return   [type]          [description]
     */
    function lock($txt,$key='ihw888888')
    {
        if (empty($txt)) {
            return $txt;
        }

        $txt = $txt.$key;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $nh = 10;
        $ch = $chars[$nh];
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey,$nh%8, $nh%8+7);
        $txt = base64_encode($txt);
        $tmp = '';
        $i=0;$j=0;$k = 0;
        for ($i=0; $i<strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
            $tmp .= $chars[$j];
        }
        return urlencode(base64_encode($ch.$tmp));
    }

    /**
     * [解密函数]
     * @Author   zt
     * @DateTime 2018-09-19
     * @param    [type]     $txt [解密内容]
     * @param    string     $key [description]
     * @return   [type]          [description]
     */
    function unlock($txt,$key='ihw888888')
    {
        if (empty($txt)) {
            return $txt;
        }
        
        $txt = base64_decode(urldecode($txt));
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $ch = $txt[0];
        $nh = strpos($chars,$ch);
        $mdKey = md5($key.$ch);
        $mdKey = substr($mdKey,$nh%8, $nh%8+7);
        $txt = substr($txt,1);
        $tmp = '';
        $i=0;$j=0; $k = 0;
        for ($i=0; $i<strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
            while ($j<0) $j+=64;
            $tmp .= $chars[$j];
        }
        return trim(base64_decode($tmp),$key);
    }
}